import pymysql
import logging

class ConnectMysql:
    def __init__(self, host, user, password, database):
        self.host = host
        self.user = user
        self.password = password
        self.database = database

    def __enter__(self):
        self.con = pymysql.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            database=self.database,
            cursorclass = pymysql.cursors.DictCursor  # 使用字典游标
        )
        self.cur = self.con.cursor()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cur.close()
        self.con.close()

    def execute_query(self, sql):
        try:
            self.cur.execute(sql)
            if sql.strip().lower().startswith('select'):
                result = self.cur.fetchall()
            else:
                self.con.commit()
                result = self.cur.rowcount
            return result
        except Exception as e:
            logging.error(f"Error executing query: {e}")
            self.con.rollback()
            raise

    def select(self, sql):
        return self.execute_query(sql)

    def delete(self, sql):
        return self.execute_query(sql)

    def insert(self, sql):
        return self.execute_query(sql)

    def update(self, sql):
        return self.execute_query(sql)

# 使用示例
if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    with ConnectMysql(host='10.51.2.4', user='pvuser', password='XH33tSm1JT0U8Jqt', database='iot_platform') as db:
        # 执行 SELECT 查询
        select_sql = "select * from pomp_power_plant_basic where power_name = '王超'"
        result = db.select(select_sql)
        print(result)
